package fulbiNet.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import fulbiNet.execpcion.DAOExcepcion;
import fulbiNet.modelo.Cliente;
import fulbiNet.util.ConexionBD;

public class ClienteDAO extends BaseDAO{


	public int insertar(Cliente vo) throws DAOExcepcion {
		
			System.out.println("CanchaDAO: insertar(Cliente vo)");
			String query = "INSERT INTO cliente(idCliente, direccion, idDistrito) VALUES (?,?,?)";
			Connection con = null;
			PreparedStatement stmt = null;
			int i=-1;
			try {
				con = ConexionBD.obtenerConexion();
				stmt = con.prepareStatement(query);
				
				stmt.setInt(1, vo.getCodigo());
				stmt.setString(2, vo.getDireccion());
				stmt.setInt(3, vo.getoDistrito().getCodigo());
				i = stmt.executeUpdate();
				if (i != 1) {
					throw new SQLException("No se pudo insertar");
				}
			} catch (SQLException e) {
				System.err.println(e.getMessage());
				throw new DAOExcepcion(e.getMessage());
			} finally {
				this.cerrarStatement(stmt);
				this.cerrarConexion(con);
			}
			return i;
		}
	
	
	public int obtenerIdCliente() throws DAOExcepcion {
		System.out.println("ClienteDAO: obtener ultimo ID generado()");
		int idPersona=0;
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String query = "select MAX(idPersona) from persona";
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				idPersona= rs.getInt(1);
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return idPersona;
	}



	
	public int buscarClientexUsuarioyMail(String nroDocumento,String email) throws DAOExcepcion {
			System.out.println("ClienteDAO: buscarClientexUsuarioyMail()");
			int resp=0;
			Connection con = null;
			PreparedStatement stmt = null;
			ResultSet rs = null;
			try {
				con = ConexionBD.obtenerConexion();
				String query = "SELECT * from Persona where nrodocumento=? and email=?";
				stmt = con.prepareStatement(query);
				stmt.setString(1,nroDocumento);
				stmt.setString(2,email);
				
				rs = stmt.executeQuery();
				while (rs.next()) {
					resp++;
				}
			} catch (SQLException e) {
				System.err.println(e.getMessage());
				throw new DAOExcepcion(e.getMessage());
			} finally {
				this.cerrarStatement(stmt);
				this.cerrarConexion(con);
			}
			return resp;
		}

}
